package loan.calc.calculator.impl;

import loan.calc.dto.LoanDTO;
import loan.calc.dto.LoanRepaySegmentDTO;
import loan.calc.util.CloneUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author v_ECD963
 */
@Component("repaySegmentTotalPeriodCalculator")
public class LoanRepaymentSegmentTotalPeriodCalculator extends AbstractCalculator {

    private static final Integer SORT_CODE = 400;

    private final LoanRepaymentSegmentNextRepayDateCalculator repaySegmentNextRepaymentDateCalculator;

    public LoanRepaymentSegmentTotalPeriodCalculator(LoanRepaymentSegmentNextRepayDateCalculator repaySegmentNextRepaymentDateCalculator) {
        this.repaySegmentNextRepaymentDateCalculator = repaySegmentNextRepaymentDateCalculator;
    }

    @Override
    public Integer calculatorSort() {
        return SORT_CODE;
    }

    @Override
    public String calculatorName() {
        return "还款区段总还款期数填充";
    }

    @Override
    public void calculate(LoanDTO loan) {
        loan.getLoanRepaySegmentList().forEach(segment -> {
            Integer currentPeriod = segment.getCurrentPeriod();
            if (Objects.isNull(currentPeriod)) {
                currentPeriod = 1;
                segment.setCurrentPeriod(currentPeriod);
            }
            LoanRepaySegmentDTO segmentCopy = CloneUtils.deepClone(segment);
            int totalPeriod = 0;
            while (segmentCopy.getLastRepaymentDate().isBefore(segmentCopy.getSegmentMaturityDate())) {
                totalPeriod++;
                segmentCopy.setLastRepaymentDate(segmentCopy.getNextRepaymentDate());
                segmentCopy.setNextRepaymentDate(repaySegmentNextRepaymentDateCalculator.doCalculate(segmentCopy));
            }
            // totalPeriod = totalPeriod + segmentCopy.getCurrentPeriod() - 1;
            printRepaymentSegmentDebugLog(segment, "总还款期数:" + totalPeriod);
            segment.setTotalPeriod(totalPeriod);
        });
    }
}
